package com.atguigu.guli.service.vod.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.req.UploadVideoRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyun.vod.upload.resp.UploadVideoResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.vod.service.VideoService;
import com.atguigu.guli.service.vod.util.VodProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * @author lsystart
 * @create2021-11-05 17:43
 */

@Service
public class VideoServiceImpl implements VideoService {

    @Autowired
    VodProperties vodProperties;

    @Override
    public String uploadVideo(InputStream file, String originalFileName) {
        try {
            UploadVideoImpl client = new UploadVideoImpl();
            UploadStreamRequest request = new UploadStreamRequest(vodProperties.getKeyId(),vodProperties.getKeySecret(),originalFileName,originalFileName,file);
            request.setTemplateGroupId(vodProperties.getTemplateGroupId());//模板ID
            request.setWorkflowId(vodProperties.getWorkflowId());

            UploadStreamResponse response = client.uploadStream(request);

            if (response.isSuccess()) {
                return response.getVideoId();
            } else{
                throw new GuliException(ResultCodeEnum.VIDEO_UPLOAD_ALIYUN_ERROR);
            }
        } catch (GuliException e) {
            throw new GuliException(ResultCodeEnum.VIDEO_UPLOAD_ALIYUN_ERROR);
        }
    }

    @Override
    public String getPlayAuth(String videoId) {
        String regionId = "cn-shanghai";  // 点播服务接入区域
        DefaultProfile profile = DefaultProfile.getProfile(regionId,vodProperties.getKeyId(),vodProperties.getKeySecret());
        DefaultAcsClient client = new DefaultAcsClient(profile);
        GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();
        try {
            //2、使用客户端根据请求信息 发送请求
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            request.setVideoId(videoId);
            request.setAuthInfoTimeout(3000L);//配置加密视频凭证的过期时间为3000秒  默认100秒
            response = client.getAcsResponse(request);
            return response.getPlayAuth();
        }catch (Exception e){
            throw new GuliException(ResultCodeEnum.FETCH_PLAYAUTH_ERROR , e);
        }
    }
}
